package com.example.interesting.distributed.log.realize.dubbo.provider;

import cn.hutool.core.util.StrUtil;
import com.example.interesting.distributed.log.realize.constant.LogConstants;
import com.example.interesting.distributed.log.realize.util.LogTraceInit;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.rpc.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: dubbo提供者过滤器
 * @Author: fyw
 * @Date: 2024/4/6 17:12
 * @History
 */
@Slf4j
public class DubboProviderFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Map<String, String> attachments = new HashMap<>();
        LogConstants.HEADER_KEYS.forEach(key -> {
            String attachment = invocation.getAttachment(key);
            if (StrUtil.isNotBlank(attachment)) {
                attachments.put(key, attachment);
            }
        });
        //首次进入需要初始化
        LogTraceInit.fillTraceId(attachments);
        log.info("RPC请求链接日志信息：traceId={}，parentName={}", attachments.get(LogConstants.LOG_TRACE_ID), attachments.get(LogConstants.PARENT_SERVICE_NAME));
        return invoker.invoke(invocation);
    }
}
